﻿using StarPizza.Model.User;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace StarPizza.ViewModel.User
{
    public class UserAuthenticator : AbstractUserData
    {
        public UserAuthenticator(UserSpace userSpace)
            : base(userSpace)
        {
            this.userSpace = userSpace;
            userSpace.AuthenticationStateChanged += userSpace_AuthenticationStateChanged;
        }

        void userSpace_AuthenticationStateChanged(AuthenticationState newState)
        {
            switch (newState)
            {
                case AuthenticationState.On:
                case AuthenticationState.Registrating:
                    IsVisible = false;
                    break;
                case AuthenticationState.Off:
                    IsVisible = true;
                    break;
            }
        }
        public static string EncryptPassword(string rawPassword)
        {
            //source: http://stackoverflow.com/questions/212510/what-is-the-easiest-way-to-encrypt-a-password-when-i-save-it-to-the-registry
            byte[] data = System.Text.Encoding.ASCII.GetBytes(rawPassword);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            String hash = System.Text.Encoding.ASCII.GetString(data);
            return hash;
        }
        public void TryAuthentication()
        {
            try
            {
                userSpace.Authenticate(Login, EncryptPassword(Password));
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    messageBoxText: e.Message,
                    caption: "Authentication error",
                    button: MessageBoxButton.OK,
                    icon: MessageBoxImage.Error
                    );
            }
            Password = "";
        }
        public void RegistrateClient()
        {
            userSpace.StartRegistration();
        }
    }
}
